/*
 * Copyright 2013 Sigurd Randoll <srandoll@digiway.de>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.server.infrastructure.persistence;

import de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage;
import de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorageFilter;
import de.digiway.rapidbreeze.server.model.download.Download;
import de.digiway.rapidbreeze.server.model.download.DownloadRepository;
import java.util.List;

/**
 * A {@linkplain DownloadRepository} implementation using JPA2. Any method will
 * startup a new Transaction if there is currently no transaction active.
 *
 * @author Sigurd Randoll <srandoll@digiway.de>
 */
public class DownloadRepositoryStorage implements DownloadRepository {

    private ObjectStorage objectStorage;

    public DownloadRepositoryStorage(ObjectStorage objectStorage) {
        this.objectStorage = objectStorage;
    }

    @Override
    public List<Download> getDownloads() {
        ObjectStorageFilter<Download> filter = objectStorage.createFilter(Download.class);
        filter.orderBy(Download.PROP_CREATED, true);
        return objectStorage.load(filter);

    }

    @Override
    public void add(final Download download) {
        objectStorage.persist(download);
    }

    @Override
    public void remove(Download download) {
        objectStorage.remove(download);
    }

    @Override
    public boolean hasDownload(String identifier) {
        if (identifier == null || identifier.isEmpty()) {
            return false;
        }
        return objectStorage.exists(Download.class, identifier);
    }

    @Override
    public Download getDownload(String identifier) {
        if (!hasDownload(identifier)) {
            throw new IllegalArgumentException("The " + Download.class.getSimpleName() + " with the given iddentifier:" + identifier + " does not exist.");
        }
        return objectStorage.load(Download.class, identifier);
    }

    @Override
    public void clearAll() {
        objectStorage.removeAll(Download.class);
    }

    @Override
    public void update(Download download) {
        objectStorage.persist(download);
    }

    @Override
    public void delete(Download download) {
        objectStorage.remove(download);
    }
}
